package com.ioidea.ble.proto

import android.annotation.SuppressLint
import com.ioidea.base.util.MyLogger
import com.ioidea.base.util.Symbol
import java.lang.Exception
import java.nio.charset.StandardCharsets

/**
 *  手机->设备 @@ + SN + ：+ 指令 + 数据 + “\r\n”
 *  设备->手机 ## + SN + ：+ 指令 + 数据 + “\r\n”
 *  注：一个完整的数据包（包含头和尾）的长度不能超过2048字节，如果超过需要分包发送
 *  @author hemin
 */
abstract class ProtoBase {

    companion object {
        //过滤蓝牙头
//        const val SMART_PLC_NAME_START = "IOIDEA LAMP"
        const val SMART_PLC_NAME_START = "SmartPlc"
        const val EMPTY_SN = "-1"

        //请求的固定头
        const val HEAD_REQUEST = "@@"

        //响应的固定头
        const val HEAD_RESPONSE = "##"

        //请求返回的尾巴
        const val TAIL = "\r\n"

        //上报数据内容
        const val REPORT_DATA_CONTENT = ":STA:"
        //设备在组下的id
        const val GROUP_CONTENT = ":STA_GROUP:"

    }

    //请求指令   请求响应有些指令不是一一对应 例如 首次获取白名单 获取全部设备的组
    abstract var requestCommand: String

    //响应指令
    abstract var responseCommand: String

    //设备sn
    var sn = ""


    /**
     * @param sn       集控器sn
     * @param payload  真正发送的数据
     */
    fun getRequestData(sn: String, payload: String): String {
        this.sn = sn
        return "$HEAD_REQUEST$sn${Symbol.MAO_HAO}$requestCommand${Symbol.MAO_HAO}$payload$TAIL"
    }


    /**
     *  指令后不加字符
     */
    fun getRequestData1(sn: String, payload: String): String {
        this.sn = sn
        return "$HEAD_REQUEST$sn${Symbol.MAO_HAO}$requestCommand$payload$TAIL"
    }

    /**
     *  指令后加空格
     */
    fun getRequestData2(sn: String, payload: String): String {
        this.sn = sn
        return "$HEAD_REQUEST$sn${Symbol.MAO_HAO}$requestCommand${Symbol.SPACE}$payload$TAIL"
    }


    fun getRequestByteData(sn: String, payloadByteData: MutableList<Byte>): ByteArray {
        val data = mutableListOf<Byte>()
        this.sn = sn
        // 头部
        data.addAll(
            "$HEAD_REQUEST$sn${Symbol.MAO_HAO}".toByteArray(StandardCharsets.US_ASCII).toList()
        )
        // 指令
        data.addAll("$requestCommand".toByteArray(StandardCharsets.US_ASCII).toList())
        // 数据
        data.addAll(payloadByteData)
        // 尾部
        data.addAll("$TAIL".toByteArray(StandardCharsets.US_ASCII).toList())
        return data.toByteArray()
    }


    /**
     * 有些没有payload 只用发指令
     */
    fun getRequestData(sn: String): String {
        this.sn = sn
        return "$HEAD_REQUEST$sn${Symbol.MAO_HAO}$requestCommand$TAIL"
    }




    /**
     * @param wholeData 从蓝牙读取的完整数据
     * @return payload
     */
    @SuppressLint("SuspiciousIndentation")
    fun removeHeadTail(wholeData: String): String {
        val head = "$HEAD_RESPONSE$sn${Symbol.MAO_HAO}$responseCommand${Symbol.MAO_HAO}"
        val head1 = "$HEAD_RESPONSE$sn${Symbol.MAO_HAO}$responseCommand${Symbol.SPACE}"
        if ((wholeData.startsWith(head) || wholeData.startsWith(head1)) && wholeData.endsWith(TAIL)) {//正确的数据
//        if (wholeData.startsWith(head)) {
            val wholeDataArray = if (wholeData.startsWith(head)) {
                wholeData.split(head)
            } else {
                wholeData.split(head1)
            }//所有的数据
            if (wholeDataArray.size == 2) {//去头
                val dataTailStr = wholeDataArray[1]//数据+尾巴
                val dataTailArray = dataTailStr.split(TAIL)//所有的数据
//                if (dataTailArray.size == 2) {
                return dataTailArray[0]
//                }
            }
        }
        return ""

    }

    /**
     *  通用解析
     *  @return 1:成功 0:失败
     */
    fun parseCommonResponse(wholeData: String): Int {
        //去头尾
        val data = removeHeadTail(wholeData)
        MyLogger.hLog().i("data:$data")
        return try {
            data.toInt()
        } catch (e: Exception) {
            MyLogger.hLog().e(e.message)
            0
        }
    }


}